// pages/login/index.js
import {loginMpWx} from '../../apis/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },
  login(){
    const can = wx.canIUse('getUserProfile')
    if (!can) {
       wx.showToast({
         title: '不允许获取用户信息',
       })
       return
    }
    const _that = this
    wx.getUserProfile({
      desc: '用于快速登录',
      success(res){
        const userInfo = res.userInfo
        _that.onAuth(userInfo)
      }
    })
  },
  goBack(){
    wx.navigateBack({
      delta: 1,
    })
  },
  getCode(){
    return new Promise((resolve, reject) => {
      wx.login({
        success(res){
         console.log("code的值是", res.code)
         resolve(res.code)
        }
     })
    })
  },
  async onAuth(userInfo){
    console.log(userInfo)
    const code = await this.getCode()
    /*
      {"partyData":{"code":"053Uf91w3N17xZ2ltP2w3PLAYh2Uf91E","oauth":"MP-WEIXIN","userInfo":{"nickName":"微信用户","gender":0,"language":"","city":"","province":"","country":"","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"}}}}
    */ 
   const partyData =  {
    code: code,
    "oauth":"MP-WEIXIN",
    userInfo: userInfo
  }
    const data = {
      form: {
        partyData: partyData
      }
    }
    console.log("data----",data)
    const loginResult = await loginMpWx({data:data})
    console.log("登录的结果", loginResult)
    const url = "/pages/rigister/index?partyData="+encodeURIComponent(JSON.stringify(partyData))
    if (loginResult.status === 500) {
       wx.navigateTo({
         url: url,
       })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})